<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="keyword"  content="">
    <link rel="shortcut icon" href="/img/logo.png">
    <!-- Place this tag in your head or just before your close body tag. -->
    <script async defer src="https://buttons.github.io/buttons.js"></script>
    <title>
        
          多线程—volatile关键字 - 宋正兵的博客 | zbsong Blog
        
    </title>

    <link rel="canonical" href="zbsong.top/article/多线程—volatile/">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <!-- Custom CSS --> 
    <link rel="stylesheet" href="/css/beantech.min.css">

    <link rel="stylesheet" href="/css/donate.css">
    
    <!-- Pygments Highlight CSS -->
    <link rel="stylesheet" href="/css/highlight.css">

    <link rel="stylesheet" href="/css/widget.css">

    <link rel="stylesheet" href="/css/rocket.css">

    <link rel="stylesheet" href="/css/signature.css">

    <link rel="stylesheet" href="/css/toc.css">

    <!-- Custom Fonts -->
    <!-- <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
    <!-- Hux change font-awesome CDN to qiniu -->
    <link href="https://cdn.staticfile.org/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">


    <!-- Hux Delete, sad but pending in China
    <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/
    css'>
    -->


    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!-- ga & ba script hoook -->
    <script></script>
</head>


<!-- hack iOS CSS :active style -->
<body ontouchstart="">
	<!-- Modified by Yu-Hsuan Yen -->
<!-- Post Header -->
<style type="text/css">
    header.intro-header{
        
            background-image: url('https://api.dujin.org/bing/1920.php')
            /*post*/
        
    }
    
</style>

<header class="intro-header" >
    <!-- Signature -->
    <div id="signature">
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                
                    <div class="post-heading">
                        <div class="tags">
                            
                              <a class="tag" href="/tags/#java" title="java">java</a>
                            
                        </div>
                        <h1>多线程—volatile关键字</h1>
                        <!-- <h2 class="subheading">volatile，volatile与synchronized保证有序性，happens-before，JMM</h2> -->
                        <span class="meta">
                            宋正兵 on
                            2021-03-15
                        </span>
                    </div>
                


                </div>
            </div>
        </div>
    </div>
</header>

    <!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header page-scroll">
            <button type="button" class="navbar-toggle">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/">songzblink</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <!-- Known Issue, found by Hux:
            <nav>'s height woule be hold on by its content.
            so, when navbar scale out, the <nav> will cover tags.
            also mask any touch event of tags, unfortunately.
        -->
        <div id="huxblog_navbar">
            <div class="navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li>
                        <a href="/">主页</a>
                    </li>
					<li>
                        <a href="/archive/">归档</a>
                    </li>
					<li>
                        <a href="/tags/">标签</a>
                    </li>
					<li>
                        <a href="/about/">关于</a>
                    </li>
					<!--
					修改about在前面的问题
                    
                        
                    
                        
                        <li>
                            <a href="/about/">关于</a>
                        </li>
                        
                    
                        
                        <li>
                            <a href="/archive/">归档</a>
                        </li>
                        
                    
                        
                        <li>
                            <a href="/tags/">标签</a>
                        </li>
                        
                    
                    -->
                </ul>
            </div>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container -->
</nav>
<script>
    // Drop Bootstarp low-performance Navbar
    // Use customize navbar with high-quality material design animation
    // in high-perf jank-free CSS3 implementation
    var $body   = document.body;
	// querySelector 获取文档中 id="demo" 的元素
    var $toggle = document.querySelector('.navbar-toggle');
    var $navbar = document.querySelector('#huxblog_navbar');
    var $collapse = document.querySelector('.navbar-collapse');

    $toggle.addEventListener('click', handleMagic)
    function handleMagic(e){
        if ($navbar.className.indexOf('in') > 0) {
        // CLOSE
            $navbar.className = " ";
            // wait until animation end.
            setTimeout(function(){
                // prevent frequently toggle
                if($navbar.className.indexOf('in') < 0) {
                    $collapse.style.height = "0px"
                }
            },400)
        }else{
        // OPEN
            $collapse.style.height = "auto"
            $navbar.className += " in";
        }
    }
</script>


    <!-- Main Content -->
    <!-- Modify by Yu-Hsuan Yen -->

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">

            <!-- Post Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                post-container">

				
                <p>参考博客：<a href="https://blog.csdn.net/zjcjava/article/details/78406330" target="_blank" rel="noopener">JMM概述</a></p>
<p>在介绍 volatile 关键字之前，我们应该先了解了解 JMM（Java 内存模型）。</p>
<h2 id="java内存模型">Java内存模型</h2>
<p>JMM 本身是一个抽象的概念，并不真实存在，它描述的是通过一组规则或规范定制了程序中各个变量（包括实例字段、静态字段和构成数组对象的元素）的访问方式。因为它不是对物理内存的规范，而是在虚拟机基础上进行的规范从而能实现平台一致性，以达到 Java 程序能够“一次编写，到处运行”。</p>
<p>由于JVM 运行程序的实体是线程，而每个线程创建时 JVM 都会为其创建一个工作内存（有些地方成为栈空间），工作内存是每个线程的私有数据区域，而 Java内存模型中规定所有变量都存储在主内存，主内存是共享内存区域，所有线程都可访问，但线程对变量的操作（读取赋值等）必须在工作内存中进行，首先要将变量从主内存拷贝到自己的工作空间，然后对变量进行操作，操作完成再将变量写回主内存，不能直接操作主内存中的变量，各个线程中的工作内存储存着主内存中的变量副本拷贝，因此不同的线程无法访问对方的工作内存，此线程间的通讯（传值） 必须通过主内存来完成。</p>
<p><img src="https://pic.tyzhang.top/images/2021/03/15/imagedceb6e4934633705.png" alt="imagedceb6e4934633705.png"></p>
<p>JMM 是围绕着在并发过程中如何处理可见性、原子性、有序性这三个特性而简历的模型。</p>
<blockquote>
<p>有时间专门整理一篇 JMM 相关内容。</p>
</blockquote>
<h3 id="原子性atomicity">原子性（Atomicity）</h3>
<blockquote>
<p>一个操作不能被打断，要么全部执行完毕，要么不执行</p>
</blockquote>
<p>基本类型数据的访问大都是原子操作，long 和 double 类型的变量是 64 位，但是在 32 位 JVM 中，32 位的 JVM 会将 64 位数据的读写操作分为 2 次 32 位的读写操作来进行，这就导致了 long、double 类型的变量在 32 位虚拟机中是非原子操作，数据有可能会被破坏，也就意味着多个线程在并发访问的时候是线程非安全的。</p>
<p>解决原子性问题（如多个线程同时操作一个共享变量），可以使用：</p>
<ul>
<li>加 synchronized 关键字</li>
<li>使用 JUC 下的 AtomicInteger 类</li>
</ul>
<h3 id="可见性visibility">可见性（visibility）</h3>
<blockquote>
<p>一个线程对共享变量做了修改之后，其他的线程立即能够看到（感知到）该变量的这种修改（变化）。</p>
</blockquote>
<p>volatile 关键字、synchronized关键字、Lock接口、final 可以实现可见性。</p>
<p>volatile 关键字的特殊规则保证了被 volatile 修饰的变量的值修改后，新值会立刻同步到主内存，每次使用被 volatile 修饰的变量时会立刻从主内存中刷新，因此 volatile 关键字可以保证多线程之间的操作变量的可见性。</p>
<p>synchronized 关键字在同步方法/同步块开始时（Monitor Enter），使用共享变量时会从主内存中刷新变量值到工作内存中；在同步方法/同步块结束时（Monitor Exit），会将工作内存中的变量值同步到主内存中去。</p>
<p>使用 Lock 接口（拿最常用的实现 ReentrantLock 重入锁）来实现可见性：在方法开始的位置执行 <code>lock（）</code> 方法，这和 synchronized 开始位置（Monitor Entry）有相同的语义，即使用共享变量时会从主内存中刷新变量值到工作内存中；在方法最后的执行 <code>unlock（）</code> 方法，和 synchronized 结束位置（Monitor Exit）有相同的语义，即将工作内存中的变量值同步到主内存中去。</p>
<p>被 final 关键字修饰的变量，在构造函数完成且构造函数中没有把 <code>this</code> 的引用传递出去时，其他线程就可以看到 final 变量的值，实现了可见性。（<code>this</code> 引用逃逸非常危险，其他的线程很可能通过引用访问到只初始化了一半的对象）</p>
<h3 id="有序性ordering">有序性（Ordering）</h3>
<blockquote>
<p>在单线程中，代码的执行时从前往后依次执行的。但是在多线程并发时，程序的执行有可能是无序的。在本线程内观察，所有操作都是有序的。如果在一个线程中观察另一个线程，所有操作都是无序的，无序是因为发生了指令重排序、工作内存和主内存同步延迟现象（单线程中不存在）。</p>
</blockquote>
<p>一个最经典的例子就是银行汇款问题，一个银行账户存款 100，这时一个人从该账户取 10 元，同时另一个人向该账户汇 10 元，那么余额应该还是 100。那么此时可能发生这种情况，A 线程负责取款，B 线程负责汇款，A 从主内存读到 100，B 从主内存读到 100，A 执行减 10 操作，并将数据刷新到主内存，这时主内存数据 $100-10=90$，而 B 内存执行加 10 操作，并将数据刷新到主内存，最后主内存数据 $100+10=110$，显然这是一个严重的问题，我们要保证 A 线程和 B 线程有序执行，先取款后汇款或者先汇款后取款，此为有序性。</p>
<p>可以通过 volatile 关键字和 synchronized 关键字来保证多线程操作的有序性，volatile 关键字通过加入内存屏障来禁止指令的重排序优化，而 synchronized 关键字通过加锁来允许同一时间只有一个线程对共享变量进行操作。</p>
<h2 id="指令重排带来的问题">指令重排带来的问题</h2>
<p>计算机在执行程序时，为了提高性能，编译器和处理器常常会进行<strong>指令重排</strong>。</p>
<p><img src="https://pic.tyzhang.top/images/2021/03/15/imagefb56c72e0dac516b.png" alt="imagefb56c72e0dac516b.png"></p>
<p>虽然处理器进行指令重排会考虑指令之间的数据依赖性，但是不同处理器之间和不同线程之间的数据依赖性不被编译器和处理器考虑。</p>
<p>对于代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> a = <span class="number">0</span>, b = <span class="number">0</span>, x = <span class="number">0</span>, y = <span class="number">0</span>;</span><br><span class="line"><span class="comment">// 线程1</span></span><br><span class="line">&#123;</span><br><span class="line">    x = a;</span><br><span class="line">    b = <span class="number">1</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 线程2</span></span><br><span class="line">&#123;</span><br><span class="line">    y = b;</span><br><span class="line">    a = <span class="number">2</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<table>
<thead>
<tr>
<th>时间片</th>
<th>线程1</th>
<th>线程2</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>x=a;</td>
<td>y=b;</td>
</tr>
<tr>
<td>1</td>
<td>b=1;</td>
<td>a=2;</td>
</tr>
</tbody>
</table>
<p>执行的结果是 <code>x = 0, y = 0</code>。</p>
<p>如果编译器对这段代码进行指令重排，可能会出现</p>
<table>
<thead>
<tr>
<th>时间片</th>
<th>线程1</th>
<th>线程2</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>b=1;</td>
<td>a=2;</td>
</tr>
<tr>
<td>1</td>
<td>x=a;</td>
<td>y=b;</td>
</tr>
</tbody>
</table>
<p>执行的结果是 <code>x = 2, y = 1</code>。</p>
<p>这也就说明在多线程环境下，由于指令重排的存在，两个线程使用的变量能否保持一致性是无法确定的。</p>
<h2 id="volatile">volatile</h2>
<p>volatile 关键字的底层实现原理是内存屏障（Memory Barrier），它能保证被修饰的变量对所有线程的可见性，还能够禁止指令重排序优化。</p>
<blockquote>
<p>volatile 仅保证可见性，有序性需要结合 synchronized 来实现。</p>
</blockquote>
<p>如果指令间插入了内存屏障，则会告诉编译器和处理器，不管什么指令都不能和这条内存屏障指令重排序，即通过插入内存屏障禁止在内存屏障前后的指令执行重排序优化。内存屏障另一个作用就是强制刷新各种缓存数据，保证线程能够读到这些数据的最新版本。</p>
<h3 id="保证内存可见性">保证内存可见性</h3>
<ul>
<li>对 volatile 变量的写指令后加入写屏障，写屏障保证在该屏障之前对 volatile 变量的改动，都同步到主内存当中</li>
<li>对 volatile 变量的读指令前加入读屏障，读屏障保证在该屏障之后，对 volatile 变量的读取，加载的都是主内存当中的新数据</li>
</ul>
<h3 id="如何保证有序性">如何保证有序性？</h3>
<ul>
<li>写屏障确保指令重排序时，不会将写屏障之前的代码排在写屏障之后</li>
<li>读屏障确保指令重排序时，不会讲读屏障之后的代码排在读屏障之前</li>
</ul>
<p>但是它还是不能够解决指令交错的问题，即并发有序性。</p>
<p>以 double-checked locking  单例模式问题为例，</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">Singleton</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">Singleton</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">    <span class="comment">// 懒汉式</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Singleton INSTANCE = <span class="keyword">null</span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title">getInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (INSTANCE == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">synchronized</span>(<span class="keyword">this</span>) &#123;</span><br><span class="line">                <span class="keyword">if</span> (INSTANCE == <span class="keyword">null</span>) &#123;</span><br><span class="line">                    INSTANC = <span class="keyword">new</span> Singleton();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> INSTANCE;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>此时它对应的部分字节码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"> 0: getstatic		#2	// 获取 INSTANCE 引用</span><br><span class="line"> 3: ofnonnull		37	// 判断不为空，跳转到 37</span><br><span class="line">……</span><br><span class="line">17: new				#3	// 创建对象，将对象引用入栈</span><br><span class="line">20: dup					// 复制一份对象引用</span><br><span class="line">21: invokespecial	#4	// 利用一个对象引用，调用构造方法</span><br><span class="line">24: putstatic		#2	// 利用一个对象引用，赋值给 static </span><br><span class="line">……</span><br><span class="line">37: getstatic		#2	// 获取 INSTANCE 引用</span><br><span class="line">INSTACE</span><br></pre></td></tr></table></figure>
<p>存在一种可能：JVM 会优化为先执行 24，再执行 21。如果恰好有两个线程 t1、t2。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">sequenceDiagram</span><br><span class="line">participant t1</span><br><span class="line">participant INSTANCE</span><br><span class="line">participant t2</span><br><span class="line"></span><br><span class="line">t1 -&gt;&gt; t1: 17: new</span><br><span class="line">t1 -&gt;&gt; t1: 20: dup</span><br><span class="line">t1 -&gt;&gt; INSTANCE: 24: putstatic（给 INSTANCE 赋值）</span><br><span class="line">t2 -&gt;&gt; INSTANCE: 0: getstatic（获取 INSTANCE 引用）</span><br><span class="line">t2 -&gt;&gt; t2: 3: ifnonnull 37（判断不为空，跳转 37 行）</span><br><span class="line">t2 -&gt;&gt; INSTANCE: 37: getstatic（获取 INSTANCE 引用）</span><br><span class="line">t2 -&gt;&gt; t2: 40: areturn（返回）</span><br><span class="line">t2 -&gt;&gt; t2: 使用对象</span><br><span class="line">t1 -&gt;&gt; t1: 21: invokespecial（调用构造方法）</span><br></pre></td></tr></table></figure>
<p>当 t1 执行到了 24 时，t2 执行到了 0 去获取 INSTANCE。此时这个 INSTANCE 已经被  t1 执行 24 给赋值了，但是还没调用构造方法进行初始化，接着 t2 判断 INSTANCE 不为空，跳转到 37 去获取 INSTANCE 的引用，然后将该引用返回，并使用 INSTANCE 对象。注意！==这里的 INSTANCE 并没有进行构造方法初始化就被使用==，这就是问题所在。</p>
<p>如何解决呢？对 INSTANCE 使用 volatile 关键字修饰即可，可以禁用指令重排，所有的写（write）操作都将发生在读（read）操作之前。（JDK 1.5 以上版本的 volatile 才会真正有效）</p>
<p>正确的代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">Singleton</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">Singleton</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">    <span class="comment">// 懒汉式</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">volatile</span> Singleton INSTANCE = <span class="keyword">null</span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title">getInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (INSTANCE == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">synchronized</span>(<span class="keyword">this</span>) &#123;</span><br><span class="line">                <span class="keyword">if</span> (INSTANCE == <span class="keyword">null</span>) &#123;</span><br><span class="line">                    INSTANC = <span class="keyword">new</span> Singleton();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> INSTANCE;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="happens-before">happens-before?</h2>

                
                <hr>
                <!-- Pager -->
                <ul class="pager">
                    
                        <li class="previous">
                            <a href="/article/多线程—CAS无锁-乐观锁/" data-toggle="tooltip" data-placement="top" title="多线程—乐观锁CAS机制">&larr; 上一篇</a>
                        </li>
                    
                    
                        <li class="next">
                            <a href="/article/阅读记录/" data-toggle="tooltip" data-placement="top" title="阅读记录">下一篇 &rarr;</a>
                        </li>
                    
                </ul>

                <br>

                <!--打赏-->
                
                <!--打赏-->

                <br>
                <!--分享-->
                
                <!--分享-->
                <br>                       
                
                <!-- require APlayer -->
                
            </div>
            
            <!-- Tabe of Content -->
            <!-- Table of Contents -->

  
    <style>
      span.toc-nav-number{
        display: none
      }
    </style>
  
    
      <aside id="sidebar">
        <div id="toc" class="toc-article">
        <strong class="toc-title">目录</strong>
        
          <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#java内存模型"><span class="toc-nav-number">1.</span> <span class="toc-nav-text">Java&#x5185;&#x5B58;&#x6A21;&#x578B;</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#原子性atomicity"><span class="toc-nav-number">1.1.</span> <span class="toc-nav-text">&#x539F;&#x5B50;&#x6027;&#xFF08;Atomicity&#xFF09;</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#可见性visibility"><span class="toc-nav-number">1.2.</span> <span class="toc-nav-text">&#x53EF;&#x89C1;&#x6027;&#xFF08;visibility&#xFF09;</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#有序性ordering"><span class="toc-nav-number">1.3.</span> <span class="toc-nav-text">&#x6709;&#x5E8F;&#x6027;&#xFF08;Ordering&#xFF09;</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#指令重排带来的问题"><span class="toc-nav-number">2.</span> <span class="toc-nav-text">&#x6307;&#x4EE4;&#x91CD;&#x6392;&#x5E26;&#x6765;&#x7684;&#x95EE;&#x9898;</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#volatile"><span class="toc-nav-number">3.</span> <span class="toc-nav-text">volatile</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#保证内存可见性"><span class="toc-nav-number">3.1.</span> <span class="toc-nav-text">&#x4FDD;&#x8BC1;&#x5185;&#x5B58;&#x53EF;&#x89C1;&#x6027;</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#如何保证有序性"><span class="toc-nav-number">3.2.</span> <span class="toc-nav-text">&#x5982;&#x4F55;&#x4FDD;&#x8BC1;&#x6709;&#x5E8F;&#x6027;&#xFF1F;</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#happens-before"><span class="toc-nav-number">4.</span> <span class="toc-nav-text">happens-before?</span></a></li></ol>
        
        </div>
      </aside>
    

                
            <!-- Sidebar Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container">

                <!-- Featured Tags -->
                
                <section>
                    <!-- no hr -->
                    <h5><a href="/tags/">标签</a></h5>
                    <div class="tags">
                       
                          <a class="tag" href="/tags/#java" title="java">java</a>
                        
                    </div>
                </section>
                

                <!-- Friends Blog -->
				<!--
                
                <hr>
                <h5>朋友们</h5>
                <ul class="list-inline">

                    
                        <li><a href="https://tyzhang.top/" target="_blank">ztygalaxy</a></li>
                    
                        <li><a href="http://www.yctang.club/" target="_blank">yctang</a></li>
                    
                        <li><a href="https://dolnw.github.io" target="_blank">JCWang</a></li>
                    
                </ul>
                
				-->
            </div>
        </div>
    </div>
</article>


<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>
<!-- anchor-js, Doc:http://bryanbraun.github.io/anchorjs/ -->
<script>
    async("https://cdn.bootcss.com/anchor-js/1.1.1/anchor.min.js",function(){
        anchors.options = {
          visible: 'hover',
          placement: 'left',
          icon: ''
        };
        anchors.add().remove('.intro-header h1').remove('.subheading').remove('.sidebar-container h5');
    })
</script>
<style>
    /* place left on bigger screen */
    @media all and (min-width: 800px) {
        .anchorjs-link{
            position: absolute;
            left: -0.75em;
            font-size: 1.1em;
            margin-top : -0.1em;
        }
    }
</style>


<!-- chrome Firefox 中文锚点定位失效-->
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<!-- smooth scroll behavior polyfill  -->
<script type="text/javascript" src="/js/smoothscroll.js"></script>
<script>
        $('#toc').on('click','a',function(a){
            // var isChrome = window.navigator.userAgent.indexOf("Chrome") !== -1;
            // console.log(window.navigator.userAgent,isChrome)
                // if(isChrome) {
                    // console.log(a.currentTarget.outerHTML);
                    // console.log($(a.currentTarget).attr("href"));
                    //跳转到指定锚点
                    // document.getElementById(a.target.innerText.toLowerCase()).scrollIntoView(true);
                    document.getElementById($(a.currentTarget).attr("href").replace("#","")).scrollIntoView({behavior: 'smooth' });
                // }
        })  
</script>


    <!-- Footer -->
    <!-- Footer -->
<footer>
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <ul class="list-inline text-center">
                
                
                
				
                

                

                
                    <li>
                        <a target="_blank"  href="https://github.com/songzblink">
                            <span class="fa-stack fa-lg">
                                <i class="fa fa-circle fa-stack-2x"></i>
                                <i class="fa fa-github fa-stack-1x fa-inverse"></i>
                            </span>
                        </a>
                    </li>
                

                

                </ul>
                <p class="copyright text-muted">
                    Copyright &copy; 宋正兵 2021 
                    <br>
                    Theme by <a href="http://www.huweihuang.com">Huwei Huang</a>
                    re-Ported by <a href="https://github.com/ztygalaxy">ztygalaxy</a>
					
                </p>
            </div>
        </div>
    </div>
</footer>

<!-- jQuery -->
<script src="/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>

<!-- Custom Theme JavaScript -->
<script src="/js/hux-blog.min.js"></script>


<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>

<!-- 
     Because of the native support for backtick-style fenced code blocks 
     right within the Markdown is landed in Github Pages, 
     From V1.6, There is no need for Highlight.js, 
     so Huxblog drops it officially.

     - https://github.com/blog/2100-github-pages-now-faster-and-simpler-with-jekyll-3-0  
     - https://help.github.com/articles/creating-and-highlighting-code-blocks/    
-->
<!--
    <script>
        async("http://cdn.bootcss.com/highlight.js/8.6/highlight.min.js", function(){
            hljs.initHighlightingOnLoad();
        })
    </script>
    <link href="http://cdn.bootcss.com/highlight.js/8.6/styles/github.min.css" rel="stylesheet">
-->


<!-- jquery.tagcloud.js -->
<script>
    // only load tagcloud.js in tag.html
    if($('#tag_cloud').length !== 0){
        async("zbsong.top/js/jquery.tagcloud.js",function(){
            $.fn.tagcloud.defaults = {
                //size: {start: 1, end: 1, unit: 'em'},
                color: {start: '#bbbbee', end: '#0085a1'},
            };
            $('#tag_cloud a').tagcloud();
        })
    }
</script>

<!--fastClick.js -->
<script>
    async("https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
        var $nav = document.querySelector("nav");
        if($nav) FastClick.attach($nav);
    })
</script>


<!-- Google Analytics -->




<!-- Baidu Tongji -->






	<a id="rocket" href="#top" class=""></a>
	<script type="text/javascript" src="/js/totop.js?v=1.0.0" async=""></script>
    <script type="text/javascript" src="/js/toc.js?v=1.0.0" async=""></script>
<!-- Image to hack wechat -->
<img src="zbsong.top/img/icon_wechat.png" width="0" height="0" />
<!-- Migrate from head to bottom, no longer block render and still work -->

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [ ["$","$"], ["\\(","\\)"] ],
            skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
            processEscapes: true
        }
    });
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax();
        for (var i = 0; i < all.length; ++i)
            all[i].SourceElement().parentNode.className += ' has-jax';
    });
</script>
<!--
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML"></script>
</body>

</html>
